#include <sys/file.h>
#include <stdio.h>
#include <stdlib.h>
#include "tlpi.h"
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>

int
main(int argc, char *argv[])
{
	int fd, lock;
	const char *lock_name;

	if(argc < 2)
		fatal("usage error\n");
	
	if((fd = open(argv[1], O_RDWR)) == -1)
		errExit("open() failed");

	lock = (argv[2][0] == 's')? LOCK_SH : LOCK_EX;
	if(argv[2][1] == 'n')
		lock |= LOCK_NB;

	lock_name = (lock & LOCK_SH)? "LOCK_SH" : "LOCK_EX";

	printf("PID %ld: requesting %s at %s\n", (long)getpid(), lock_name, curTime("%T"));

	if(flock(fd, lock) == -1)
	{
		if(errno == EWOULDBLOCK)
		{
			printf("PID %ld: already locked, bye\n", (long)getpid());
			exit(EXIT_FAILURE);
		}
		else
			errExit("flock() failed");
	}

	printf("PID %ld: got %s at %s\n", (long)getpid(), lock_name, curTime("%T"));

	sleep(argc > 3? atoi(argv[3]) : 10);

	printf("PID %ld: release %s at %s\n", (long)getpid(), lock_name, curTime("%T"));

	if(flock(fd, LOCK_UN) == -1)
		errExit("flock() LOCK_UN failed");
	
	exit(EXIT_SUCCESS);
}
